package com.example.smartcity_poverty.ui.AllService.JobSearch.fragment

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.App.Companion.url
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.ServiceBean.JobSearchBean.JSMoreModel
import com.example.smartcity_poverty.logic.ServiceBean.JobSearchBean.JsListModel
import com.example.smartcity_poverty.logic.ServiceBean.JobSearchBean.JsMeListModel
import com.example.smartcity_poverty.logic.model.BannerModel
import com.example.smartcity_poverty.logic.util.Util.glide
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.ui.AllService.JobSearch.activtiy.JsMeAddActivity
import com.example.smartcity_poverty.ui.AllService.JobSearch.adapter.JsListAdapter
import com.example.smartcity_poverty.ui.AllService.JobSearch.adapter.JsMeListAllAdapter
import com.example.smartcity_poverty.ui.AllService.JobSearch.adapter.JsMoreAdapter
import com.example.smartcity_poverty.ui.AllService.JobSearch.model.JsMeListEntity
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_job_search.*
import kotlinx.android.synthetic.main.re_js_more.*
import kotlinx.coroutines.Dispatchers

/**
 * 找工作
 */
class JobSearchFragment : Fragment() {

    companion object {
        var jobSearchId = 0

        var arrayListName: String? = null

        var jsUserId: String? = null
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_job_search, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        runThread()

        if (jobSearchId == 10) jsLayout1.visibility = View.VISIBLE
        else jsLayout1.visibility = View.GONE


        if (jobSearchId == 30) jsLayout2.visibility = View.VISIBLE
        else jsLayout2.visibility = View.GONE

        if (jobSearchId == 20) jsLayout3.visibility = View.VISIBLE
        else jsLayout3.visibility = View.GONE

        // 点击修改个人简历
        jsMeAdd.setOnClickListener {
            startActivity(
                Intent(context, JsMeAddActivity::class.java).putExtra(
                    "userId",
                    jsUserId.toString()
                )
            )
        }
    }

    private fun runThread() = coroutine(Dispatchers.IO) {
        // setBanner
        setBanner()

        // 工作More
        setMore()

        // 职位列表展示
        setList()

        // 搜索职位实现
        setSeekList()

        // 查询个人信息
        setMeList()

        // 查询已投递简历列表
        setJsMeListAll()
    }


    /**
     * 轮播图
     */
    private suspend fun setBanner() {
        api.getBanner(mapOf("pageNum" to 1, "pageSize" to 8, "type" to 2)).apply {
            if (this.code == "200") {
                val rows = this.rows
                activity?.runOnUiThread {
                    jsBanner.apply {
                        this.adapter = object :
                            BannerImageAdapter<BannerModel.RowsBean>(ArrayList<BannerModel.RowsBean>().apply {
                                this.addAll(rows!!)
                            }) {
                            override fun onBindView(
                                p0: BannerImageHolder?,
                                p1: BannerModel.RowsBean?,
                                p2: Int,
                                p3: Int
                            ) {
                                glide(url + p1?.advImg, p0?.imageView!!)
                            }
                        }
                        this.addBannerLifecycleObserver(this@JobSearchFragment).indicator =
                            CircleIndicator(context)
                        this.setBannerRound(25f)
                    }
                }

            }
        }

    }


    /**
     * 以9宫格方式显示职位名称
     */
    private suspend fun setMore() {
        if (getToken().isNotEmpty()) {
            api.getJSMore(getToken()).apply {
                if (this.code == 200) {
                    val rows = this.rows
                    activity?.runOnUiThread {
                        jsMoreRv.apply {
                            this.layoutManager = GridLayoutManager(context, 3).apply {
                                this.orientation = GridLayoutManager.HORIZONTAL
                            }
                            this.adapter =
                                JsSeekMoreAdapter(ArrayList<JSMoreModel.RowsBean>().apply {
                                    this.addAll(rows!!)
                                }, R.layout.re_js_more)
                        }
                    }
                } else activity?.runOnUiThread { this.msg?.show() }
            }
        } else activity?.runOnUiThread { "请先登录!".show() }
    }


    /**
     * 职位列表展示
     */
    private val arrayList = ArrayList<JsListModel.RowsBean>()
    private suspend fun setList() {
        arrayList.clear()
        if (getToken().isNotEmpty()) {
            api.getJsList(getToken()).apply {
                if (this.code == 200) {
                    arrayList.addAll(this.rows!!)
                    activity?.runOnUiThread {
                        jsListRv.apply {
                            this.isNestedScrollingEnabled = false
                            this.layoutManager = LinearLayoutManager(context)
                            this.adapter = JsListAdapter(arrayList, R.layout.re_js_list)
                            this.adapter?.notifyItemChanged(arrayList.size)
                        }
                    }
                } else activity?.runOnUiThread { this.msg?.show() }
            }
        } else activity?.runOnUiThread { "请先登录".show() }
    }


    /**
     * 搜索职位实现
     */
    private suspend fun setSeekList() {
        jsSeek.setOnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                arrayList.clear()
                if (jsSeek.text.toString().isNotEmpty()) {
                    coroutine(Dispatchers.Main) {
                        api.getJsSeekList(getToken(), jsSeek.text.toString()).apply {
                            if (this.code == 200) {
                                arrayList.addAll(this.rows!!)

                                // 更新列表数据
                                activity?.runOnUiThread {
                                    jsListRv.apply {
                                        this.isNestedScrollingEnabled = false
                                        this.layoutManager = LinearLayoutManager(context)
                                        this.adapter = JsListAdapter(arrayList, R.layout.re_js_list)
                                        this.adapter?.notifyItemChanged(arrayList.size)
                                    }
                                }

                            } else activity?.runOnUiThread { this.msg?.show() }
                        }
                    }
                } else activity?.runOnUiThread { "不能为空！".show() }
            }
            false
        }
    }


    /**
     * 点击更新职位
     */
    fun setAddUpDataList(name: String) {
        coroutine(Dispatchers.Main) {
            if (getToken().isNotEmpty()) {
                api.getJsSeekList(getToken(), name).apply {
                    if (this.code == 200) {
                        arrayList.clear()
                        arrayList.addAll(this.rows!!)

                        // 更新列表数据
                        activity?.runOnUiThread {
                            jsListRv.apply {
                                this.isNestedScrollingEnabled = false
                                this.layoutManager = LinearLayoutManager(context)
                                this.adapter = JsListAdapter(arrayList, R.layout.re_js_list)
                                this.adapter?.notifyItemChanged(arrayList.size)
                            }
                        }

                    } else activity?.runOnUiThread { this.msg?.show() }
                }
            } else activity?.runOnUiThread { "请先登录！".show() }
        }

    }

    inner class JsSeekMoreAdapter(
        val list: MutableList<JSMoreModel.RowsBean>,
        layoutId: Int
    ) : BaseRecyclerAdapter<JSMoreModel.RowsBean>(list, layoutId) {
        override fun setData(
            view: BaseViewHolder.ViewFind,
            data: JSMoreModel.RowsBean,
            position: Int,
            holder: BaseViewHolder
        ) {
            val d = list[position]
            val fv = holder.viewFind
            val con = holder.viewFind.view?.context


            fv.jsMoreTitle.text = d.professionName

            holder.itemView.setOnClickListener {
                setAddUpDataList(d.professionName.toString())
            }
        }
    }


    // ----------------------------------------------------------------------------------------------------------------


    /**
     * Me
     */

    /**
     * 查询个人信息
     */
    private suspend fun setMeList() {
        if (getToken().isNotEmpty()) {
            api.loginAll(getToken()).apply {
                if (this.code == 200) {
                    this.user?.let {
                        activity?.runOnUiThread {
                            jsMeTv1.text = "用户昵称: ${it.userName}"
                            if (it.sex.toString() == "0") jsMeTv2.text = "性别: 男"
                            if (it.sex.toString() == "1") jsMeTv2.text = "性别: 女"
                            jsMeTv3.text = "邮件: ${it.email}"
                            jsMeTv4.text = "电话号码: ${it.phonenumber}"
                            jsUserId = it.userId.toString()
                        }
                    }
                } else activity?.runOnUiThread { this.msg?.show() }
            }
        } else activity?.runOnUiThread { "请先登录！".show() }
    }


    // ----------------------------------------------------------------------------------------------------------------


    /**
     * 查询投递简历
     */
    private val arrayMeListAll = ArrayList<JsMeListEntity>().apply {
        this.add(JsMeListEntity("java开发", "腾讯科技", "15K", "2023-4-12 12:26"))
        this.add(JsMeListEntity("C#开发", "腾讯科技", "15K", "2023-4-12 12:26"))
        this.add(JsMeListEntity("c/C++开发", "腾讯科技", "15K", "2023-4-12 12:26"))
    }

    private suspend fun setJsMeListAll() {
        activity?.runOnUiThread {
            jsMeListRv.apply {
                this.isNestedScrollingEnabled = false
                this.layoutManager = LinearLayoutManager(context)
                this.adapter = JsMeListAllAdapter(arrayMeListAll, R.layout.re_js_me_list)
                this.adapter?.notifyItemChanged(arrayMeListAll.size)
            }
        }
    }


}